var model = require('../model');
var Manager = model.Manager;

var tools = require('../common/tools');
var validator = require('validator');

var authMiddleWare = require('../middlewares/auth');
var config = require('../config');

exports.login = function(req, res) {
    res.render('backend/sign/login', {
        title: "登录"
    });
};

exports.createSession = function(req, res, next) {
    var email = validator.trim(req.body.email).toLowerCase();
    var password = validator.trim(req.body.password);
    var readme = req.body.readme;

    Manager.findOne({
        'email': email
    }, function(error, manager) {
        if (error) {
            console.log(error);
            return;
        }
        if (!manager) {
            res.json({
                success: false,
                errors: [{
                    message: "用户名或密码错误"
                }]
            });
            return;
        }
        var passhash = manager.password;

        tools.bcompare(password, passhash, function(error, bool) {
            if (error) {
                console.log(error);
                return;
            }
            if (!bool) {
                res.json({
                    success: false,
                    errors: [{
                        message: "用户名或密码错误"
                    }]
                });
                return;
            }
            if(readme){
                authMiddleWare.generateManagerSession(manager, res);
            }
            req.session.manager = manager;
            res.append('Location', '/backend');
            res.json({
                success:true
            });
        });
    });
};

exports.logout = function(req, res, next) {
    req.session.destroy();
    res.clearCookie(config.cookie_backend, {
        path: '/'
    });
    res.redirect('/backend');
};